<template>
  <transition name="alert-fade">
    <div v-if="visible" class="ship-alarm-notification" :class="{ 'is-expanded': expanded }">
      <div class="alarm-header" @click="toggleExpand">
        <div class="alarm-icon">
          <el-icon><WarningFilled /></el-icon>
        </div>
        <div class="alarm-title">
          <span>船舶告警 ({{ alarmCount }})</span>
        </div>
        <div class="alarm-actions">
          <el-icon class="expand-icon" :class="{ 'is-expanded': expanded }"><ArrowDown /></el-icon>
          <el-icon class="close-icon" @click.stop="close"><Close /></el-icon>
        </div>
      </div>
      
      <div v-if="expanded" class="alarm-content">
        <div v-for="(alarm, index) in alarms" :key="alarm.id || index" class="alarm-item">
          <div class="alarm-item-header">
            <span class="ship-name">{{ alarm.shipName || alarm.mmsi }}</span>
            <span class="warning-level" :class="getWarningLevelClass(alarm.warningLv)">
              {{ alarm.warningLv || '预警' }}
            </span>
          </div>
          <div class="alarm-item-content">
            {{ alarm.eventContent || '未知告警内容' }}
          </div>
          <div class="alarm-item-footer">
            <span class="alarm-time">{{ formatTime(alarm.createTime) }}</span>
            <el-button 
              type="primary" 
              size="small" 
              @click="handleAlarm(alarm)"
            >处理</el-button>
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { WarningFilled, ArrowDown, Close } from '@element-plus/icons-vue';
import emitter from '@/utils/bus';

// 定义告警对象类型
interface ShipAlarm {
  id?: number;
  mmsi: string;
  shipName?: string;
  shipType?: string;
  eventContent?: string;
  address?: string;
  lon?: number;
  lat?: number;
  warningLv?: string;
  createTime?: string;
  [key: string]: any;
}

// 组件状态
const visible = ref(false);
const expanded = ref(true);
const alarms = ref<ShipAlarm[]>([]);
const alarmSound = ref<HTMLAudioElement | null>(null);

// 计算属性
const alarmCount = computed(() => alarms.value.length);

// 格式化时间
function formatTime(timeStr: string | undefined): string {
  if (!timeStr) return '未知时间';
  
  try {
    // 尝试提取时间部分
    const date = new Date(timeStr);
    return date.toLocaleTimeString();
  } catch (e) {
    return timeStr;
  }
}

// 获取预警级别样式类
function getWarningLevelClass(level: string | undefined): string {
  if (!level) return 'warning-normal';
  
  if (level.includes('一级')) {
    return 'warning-high';
  } else if (level.includes('二级')) {
    return 'warning-medium';
  } else if (level.includes('三级')) {
    return 'warning-low';
  } else {
    return 'warning-normal';
  }
}

// 切换展开/折叠状态
function toggleExpand(): void {
  expanded.value = !expanded.value;
}

// 关闭通知
function close(): void {
  visible.value = false;
  alarms.value = [];
}

// 处理告警
function handleAlarm(alarm: ShipAlarm): void {
  // 发送处理告警的事件
  emitter.emit('handle-ship-alarm', alarm);
  
  // 关闭通知
  close();
}

// 显示告警信息
function showAlarms(newAlarms: ShipAlarm[]): void {
  if (!newAlarms || newAlarms.length === 0) {
    return;
  }
  
  // 更新告警列表
  alarms.value = [...newAlarms];
  
  // 显示通知
  visible.value = true;
  expanded.value = true;
  
  // 播放告警声音
  playAlarmSound();
}

// 播放告警声音
function playAlarmSound(): void {
  try {
    if (alarmSound.value) {
      alarmSound.value.currentTime = 0;
      alarmSound.value.play().catch(err => {
        console.warn('无法播放告警声音:', err);
      });
    }
  } catch (error) {
    console.error('播放告警声音失败:', error);
  }
}

// 组件挂载时
onMounted(() => {
  // 创建告警声音元素
  try {
    alarmSound.value = new Audio('/alarm.mp3');
    alarmSound.value.volume = 0.5;
  } catch (error) {
    console.warn('创建告警声音失败:', error);
  }
  
  // 注册事件监听
  emitter.on('ship-alarm-triggered', showAlarms);
});

// 组件卸载时
onUnmounted(() => {
  // 清理事件监听
  emitter.off('ship-alarm-triggered', showAlarms);
  
  // 清理音频资源
  if (alarmSound.value) {
    alarmSound.value.pause();
    alarmSound.value = null;
  }
});

// 声明事件
defineExpose({
  showAlarms
});
</script>

<style scoped>
.ship-alarm-notification {
  position: fixed;
  top: 20px;
  right: 20px;
  width: 380px;
  min-height: 60px;
  background-color: rgba(31, 45, 61, 0.95);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  z-index: 9999;
  color: #fff;
  border-left: 4px solid #E6A23C;
  overflow: hidden;
  transition: all 0.3s ease;
  backdrop-filter: blur(5px);
}

.ship-alarm-notification.is-expanded {
  max-height: 500px;
}

.alarm-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  background-color: rgba(31, 45, 61, 0.8);
}

.alarm-icon {
  margin-right: 12px;
  font-size: 22px;
  color: #E6A23C;
  display: flex;
  align-items: center;
}

.alarm-title {
  flex: 1;
  font-size: 16px;
  font-weight: 600;
}

.alarm-actions {
  display: flex;
  align-items: center;
}

.expand-icon {
  margin-right: 12px;
  font-size: 18px;
  transition: transform 0.3s ease;
}

.expand-icon.is-expanded {
  transform: rotate(180deg);
}

.close-icon {
  font-size: 18px;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.close-icon:hover {
  transform: scale(1.1);
}

.alarm-content {
  padding: 0 16px 16px;
  max-height: 400px;
  overflow-y: auto;
}

.alarm-item {
  margin-top: 12px;
  padding: 12px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  border-left: 3px solid #E6A23C;
}

.alarm-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.ship-name {
  font-weight: 600;
  color: #fff;
}

.warning-level {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
}

.warning-high {
  background-color: rgba(245, 108, 108, 0.2);
  color: #F56C6C;
}

.warning-medium {
  background-color: rgba(230, 162, 60, 0.2);
  color: #E6A23C;
}

.warning-low {
  background-color: rgba(144, 147, 153, 0.2);
  color: #909399;
}

.warning-normal {
  background-color: rgba(64, 158, 255, 0.2);
  color: #409EFF;
}

.alarm-item-content {
  margin-bottom: 8px;
  color: #DCDFE6;
  line-height: 1.5;
  word-break: break-word;
}

.alarm-item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.alarm-time {
  color: #909399;
  font-size: 12px;
}

/* 动画效果 */
.alert-fade-enter-active,
.alert-fade-leave-active {
  transition: all 0.5s ease;
}

.alert-fade-enter-from,
.alert-fade-leave-to {
  opacity: 0;
  transform: translateX(30px);
}
</style> 